#include "PetFactory.h"
#include "CNumber.h"
#include "SpriteAnimation.h"
#include "xml_tag.h"



PetFactory::PetFactory(void)
{
	_id = NULL;
	_listWeapon = NULL;
	_resource = NULL;
}


PetFactory::~PetFactory(void)
{
	CC_SAFE_RELEASE(_id);
	CC_SAFE_RELEASE(_listWeapon);
	CC_SAFE_RELEASE(_resource);
}

bool PetFactory::init()
{
	setWeapons(CCArray::create());
	setResource(CCDictionary::create());

	return true;
}

void PetFactory::parseXml(xml_node node)
{
	char* id = (char*)node.child(XMLTAG_ID).text().as_string();
	setId(ccs(id));

	xml_node weapons = node.child(XMLTAG_WEAPONS);
	for (xml_node i = weapons.child(XMLTAG_ID); i; i = i.next_sibling(XMLTAG_ID))
	{
		_listWeapon->addObject(ccs(i.text().as_string()));
	}

	xml_node resource = node.child(XMLTAG_RESOURCE);
	char* texture = (char*)resource.child(XMLTAG_RESOURCE_TEXTURE).text().as_string();
	char* plist = (char*)resource.child(XMLTAG_RESOURCE_PLIST).text().as_string();
	char* prefix = (char*)resource.child(XMLTAG_RESOURCE_PREFIX).text().as_string();
	int from = resource.child(XMLTAG_RESOURCE_FROM).text().as_int();
	int to = resource.child(XMLTAG_RESOURCE_TO).text().as_int();

	_resource->setObject(ccs(texture), XMLTAG_RESOURCE_TEXTURE);
	_resource->setObject(ccs(plist), XMLTAG_RESOURCE_PLIST);
	_resource->setObject(ccs(prefix), XMLTAG_RESOURCE_PREFIX);
	_resource->setObject(CCNumber<int>::create(from), XMLTAG_RESOURCE_FROM);
	_resource->setObject(CCNumber<int>::create(to), XMLTAG_RESOURCE_TO);
}

Pet* PetFactory::createPet()
{
	CCObject* it, *it2;
	Pet* pet = Pet::create();
	pet->setId(_id);
	
	char* texture = (char*)dynamic_cast<CCString*>(_resource->objectForKey(XMLTAG_RESOURCE_TEXTURE))->getCString();
	char* plist = (char*)dynamic_cast<CCString*>(_resource->objectForKey(XMLTAG_RESOURCE_PLIST))->getCString();
	char* prefix = (char*)dynamic_cast<CCString*>(_resource->objectForKey(XMLTAG_RESOURCE_PREFIX))->getCString();
	int from = dynamic_cast<CCNumber<int>*>(_resource->objectForKey(XMLTAG_RESOURCE_FROM))->getNumber();
	int to = dynamic_cast<CCNumber<int>*>(_resource->objectForKey(XMLTAG_RESOURCE_TO))->getNumber();

	SpriteAnimation* spriteAni1 = SpriteAnimation::createWith(texture, plist, prefix, from, to);
	spriteAni1->playAnimation(true);
	pet->addChild(spriteAni1);
	pet->setContentSize(spriteAni1->getContentSize());
	pet->setSupportedWeapon(CCArray::createWithArray(_listWeapon));

	return pet;
}
